<!--
 * @Descripttion: 表格选择组件 请勿擅自修改
 * @version: 1.1
 * @Author: Lome
 * @Date: 2020-05-06 12:31:51
 * @LastEditors: Lome
 * @LastEditTime: 2020-05-13 19:33:00
 -->

<template>
  <el-dialog
    :title="tableConfig.title"
    :visible.sync="onOff"
    :width="tableConfig.dialogWidth"
    :before-close="handleClose"
    :close-on-click-modal="false"
    class="selectedTable"
  >
    <slot name="header"></slot>
    <el-row class="wrapper">
      <el-table
        :data="selectedTableDate"
        ref="goodsTable"
        style="width: 100%"
        :max-height="tableHeight"
        border=""
        :row-style="{'height':'20px'}"
        :cell-style="{'padding':'2px 0'}"
        @selection-change="selectionChange"
        @select="handelSelect"
        @select-all="handelSelectAll"
        :row-key="tableConfig.KeyWords"
        :class="tableConfig.selectionType==1?'radioStyle':''"
        v-loading="tableConfig.showLoading"
        :element-loading-text="tableConfig.showLoadingText"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
      >
        <el-table-column
          type="selection"
          width="50"
          :reserve-selection="true"
          :selectable="checkSelectable"
          v-if="tableConfig.showSelection"
        ></el-table-column>
        <el-table-column
          v-if="tableConfig.showIndex"
          label="序号"
          type="index"
          width="50"
          align="center"
        >
          <template scope="scope">
            <span>{{(current - 1) * size + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item,index) in tableConfig.tableColumn"
          :key="index"
          :prop="item.prop"
          :label="item.name"
          :width="item.width"
          :show-overflow-tooltip="item.showTip"
        >
          <template slot-scope="scope">
            <span v-if="item.type!=='click'">{{scope.row[item.prop]}}</span>
            <!-- <span>{{item}}</span> -->
            <div v-if="item.type=='click'">
              <el-button
                type="text"
                v-for="(i,index) in item.text"
                :key="index"
                @click="handelClickRow(i,scope)"
              >{{i}}</el-button>
            </div>
            <ex-slot
              v-if="item.render"
              :render="item.render"
              :row="scope.row"
              :index="scope.$index"
            />
          </template>
        </el-table-column>
      </el-table>
      <slot name="pagination"></slot>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit">{{tableConfig.ConfirmButtonText}}</el-button>
      <el-button @click="handleClose">{{tableConfig.CancelButtonText}}</el-button>
    </span>
  </el-dialog>
</template>

<script>
var _ = require('lodash')
// 自定义内容的组件
  var exSlot = {
    functional: true,
    props: {
      row: Object,
      render: Function,
      index: Number,
      column: {
        type: Object,
        default: null
      }
    },
    render: (h, data) => {
      const params = {
        row: data.props.row,
        index: data.props.index
      }
      if (data.props.column) params.column = data.props.column
      return data.props.render(h, params)
    }
  }
 export default {
  name: 'c_selectedTable',
  components: {
    exSlot
  },
  props:{
    onOff:{
      type:Boolean
    },
    tableConfig:{
      type:Object,
      required:true
    },
    checkedselectedTableDate:{ //需要回显的数据
      type:Array,
      default:()=>{
        return []
      }
    },
    selectedTableDate:{ //表格数据
      type:Array,
      default:()=>{
        return []
      }
    },
    current:{
      type:Number,
      default:()=>{
        return 1
      }
    },
    size:{
      type:Number,
      default:()=>{
        return 0
      }
    },
  },
  data () {
   return {
    totalElements:0,
    // getRowKeys(row) { //指定唯一属性
    //   return row.uuid;
    // },
    checkedGoods:[],//已勾选数据
    oldRow:{},//单选暂存数据 勿用于其他地方
    tableHeight:0,//table高度
   }
  },
  watch:{
    onOff(val){
      if(val){
        if(this.tableConfig.selectionType==1 && this.checkedselectedTableDate.length>0){
          this.oldRow = this.checkedselectedTableDate[0]
        }

        // 获取到数组调用回显方法
        if(this.tableConfig.selectionType==1){
          // 单选
          this.checkedselectedTableDate[0] && this.SentencedToHeavyField([this.checkedselectedTableDate[0]],this.selectedTableDate)
        }else{
          // 多选
          this.SentencedToHeavyField(this.checkedselectedTableDate,this.selectedTableDate)
        }

        // 更具屏幕修改table的高度
        this.$nextTick(()=>{
          this.tableHeight = window.innerHeight - 300;
        })
      }
    },
    // 监听表格数据变化 做回显
    selectedTableDate(val){
      console.log('表格数据',val)
      //把已选数据禁选掉
      let keyWords = this.tableConfig.KeyWords
      this.selectedTableDate.forEach((m,index)=>{
        this.checkedselectedTableDate.forEach(n=>{
          if(m[keyWords]==n[keyWords]){
            m.disabled = true
            if(this.onOff){
              console.log('回显数据',this.selectedTableDate[index])
              this.$nextTick(()=>{
                this.$refs.goodsTable.toggleRowSelection(this.selectedTableDate[index],true)
              })
            }
          }
        })
      })
    }
  },
  mounted() {

  },
  methods: {
    handelSelection(val){
      console.log('val',val)
    },
    handelClickRow(i,scope){
      this.$emit('handelClickRow',i,scope)
    },
    handleSubmit(){
      if(this.tableConfig.selectionType==1){
        this.$emit('submitGoods',[this.oldRow])
      }else{
        this.$emit('submitGoods',this.checkedGoods)
      }
      this.handleClose()
    },
    // 判断是否有需要回显
    SentencedToHeavyField(oldDate,newDate){
      let key = this.tableConfig.KeyWords
      // oldDate 回显的数据,newDate 本页的数据 类型数组
      if(oldDate.length>0&&newDate.length>0){
        newDate.forEach((m,index)=>{
          oldDate.forEach(n=>{
            if(m[key]==n[key]){
              this.$nextTick(()=>{
                // 回显
                this.$refs.goodsTable.toggleRowSelection(newDate[index],true)
                // 添加禁选字段
                m.disabled = this.tableConfig.disableSelect?true:false
              })
            }
          })
        })
      }
    },
    handleClose(){
      this.$emit('update:onOff',false)
      // 清除选择
      this.$refs.goodsTable.clearSelection();
    },
    handelSelectAll(rows){
      let key = this.tableConfig.KeyWords
      let newArr = _.cloneDeep(rows)
      // 去除已选的数据后做判断
      newArr.forEach((aa,index)=>{
        this.checkedselectedTableDate.forEach(bb=>{
          if(aa[key] == bb[key]){
            newArr.splice(index,1)
          }
        })
      })
      if(newArr.length>0){
        // console.log('全选')
        this.$emit('CheckWhetherThe',true,newArr)
      }else{
        // console.log('取消全选')
        this.$emit('CheckWhetherThe',false,[])
      }
    },
    // 表格选择相关事件
    handelSelect(rows,row){
      let selected = rows.length && rows.indexOf(row) !== -1
      // console.log('是否勾选',selected,rows,row)
      this.$emit('CheckWhetherThe',selected,[row]) //第一个参数勾选ro取消勾选 第二个勾选or取消勾选的数据

      let key  = this.tableConfig.KeyWords
      // console.log('select',rows,row)
      // 单选处理方法 1、将第一次勾的保存oldRow 2、勾选当前的 3、清除第一个勾选的 把当前的勾选再赋值为oldRow
      if(this.tableConfig.selectionType==1){
        if(JSON.stringify(this.oldRow)!=='{}'){
          let index = this.selectedTableDate.findIndex(e=>e[key] == this.oldRow[key])
          if(index>-1){
            // 取消禁选
            this.selectedTableDate[index].disabled = false
            // 取消勾选
            this.$refs.goodsTable.toggleRowSelection(this.selectedTableDate[index],false)
          }
        }
        this.$refs.goodsTable.toggleRowSelection(row,true)
        this.oldRow =row
      }

    },
    selectionChange(rows){
      rows = this.uniqeByKeys(rows, [this.tableConfig.KeyWords]);
      console.log('selectionChange',rows)
      this.checkedGoods = rows
    },
    // 禁止选择
    checkSelectable(row){
      return !row.disabled //将disbaled为false
    },
    //去重
    obj2key(obj, keys){
      var n = keys.length,
      key = [];
      while(n--){
      key.push(obj[keys[n]]);
      }
      return key.join('|');
    },
    uniqeByKeys (array,keys) {
      var arr = [];
      var hash = {};
      for (var i = 0, j = array.length; i < j; i++) {
      var k = this.obj2key(array[i], keys);
      if (!(k in hash)) {
      hash[k] = true;
      arr.push(array[i]);
      }
      }
      return arr ;
    },
  }
 }
</script>

<style lang='scss'>
.radioStyle {
  .el-table__header-wrapper .el-checkbox .el-checkbox__input { // 找到表头那一行，然后把里面的复选框隐藏掉
    display: none;
  }

  .el-table__header .el-table-column--selection .cell:after {
    color: #909399;
    content: '单选';
    font-size: 14px;
    font-weight: 700;
  }
}

.selectedTable {
  .el-dialog {
    position: absolute;
    top: 50%;
    left: 50%;
    margin: 0 !important;
    transform: translate(-50%, -50%);
    max-height: calc(100% -30%);
    max-width: calc(100% -30%);
    display: flex;
    flex-direction: column;

    > .el-dialog__body {
      overflow: auto;
      color: #666;
    }
  }
  /*核心代码*/
	.el-table__body-wrapper::-webkit-scrollbar {/*滚动条整体样式*/
		width: 4px; /*高宽分别对应横竖滚动条的尺寸*/
		height: 4px;
	}
	.el-table__body-wrapper::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
		border-radius: 5px;
		-webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
		background: rgba(156, 156, 156, 0.6)
	}
	.el-table__body-wrapper::-webkit-scrollbar-track {/*滚动条里面轨道*/
		-webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
		border-radius: 0;
		background: rgba(236, 229, 229, 0.4);
	}
}
</style>
